package edu.sias.chat.endpoint;

import com.fasterxml.jackson.core.JsonProcessingException;
import edu.sias.chat.config.TokenSubprotocolConfigurator;
import edu.sias.chat.entity.ChatMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@ServerEndpoint(value = "/chat", configurator = TokenSubprotocolConfigurator.class)
public class ChatEndpoint {

    // 存储在线用户的 Session：userId -> Session
    private static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
    private ObjectMapper mapper = new ObjectMapper();

    // 获取在线用户名列表
    public static List<String> getOnlineUsernames() {
        return new ArrayList<>(sessions.keySet());
    }

    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws JsonProcessingException {
        String username = (String) session.getUserProperties().get("username");
        if (username == null) {
            throw new IllegalArgumentException("用户未认证");
        }
        sessions.put(username, session);
        log.info("用户连接至聊天室，username: {}", username);

        //当有新用户进入聊天室，通知所有前端刷新在线用户列表
        String msgJson = mapper.writeValueAsString(new ChatMessage("group", "hyzn-system", "", username + "进入聊天室"));
        onMessage(msgJson, session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            String username = (String) session.getUserProperties().get("username");
            ChatMessage chatMessage = mapper.readValue(message, ChatMessage.class);
            if (!"hyzn-system".equals(chatMessage.getSender())){
                chatMessage.setSender(username); // 自动填充发送者
            }

            if ("private".equals(chatMessage.getType())) {
                Session targetSession = sessions.get(chatMessage.getTarget());
                if (targetSession != null) {
                    targetSession.getBasicRemote().sendText(mapper.writeValueAsString(chatMessage));
                }
            } else if ("group".equals(chatMessage.getType())) {
                sessions.values().forEach(s -> {
                    try {
                        s.getBasicRemote().sendText(mapper.writeValueAsString(chatMessage));
                    } catch (IOException e) {
                        log.error("消息发送失败", e);
                    }
                });
            }
        } catch (IOException e) {
            log.error("消息解析失败", e);
        }
    }

    @OnClose
    public void onClose(Session session) throws JsonProcessingException {
        String username = (String) session.getUserProperties().get("username");
        sessions.remove(username);
        log.info("用户离开聊天室，username: {}", username);

        //当有用户离开聊天室，通知所有前端刷新在线用户列表
        String msgJson = mapper.writeValueAsString(new ChatMessage("group", "hyzn-system", "", username + "离开聊天室"));
        onMessage(msgJson, session);
    }

    @OnError
    public void onError(Throwable error, Session session) {
        String username = (String) session.getUserProperties().get("username");
        log.error("用户发生错误，username: {}", username, error);
    }
}

